package cn.kgc.ywz.smbms.web.web;

import cn.kgc.ywz.smbms.web.entity.Role;
import cn.kgc.ywz.smbms.web.entity.User;
import cn.kgc.ywz.smbms.web.service.RoleService;
import cn.kgc.ywz.smbms.web.service.UserService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private RoleService roleService;

    /**
     * 查询
     */
    @RequestMapping("/show")
    public String toList(User condition, Integer pageNum, Integer pageSize, Model model) {
        //调用方法
        List<Role> roleList = this.roleService.findRole();
        PageInfo<User> pageInfo = this.userService.findAllOrCondition(condition, pageNum, pageSize);

        //存储数据
        model.addAttribute("userName", condition.getUserName());    //输入用户名称
        model.addAttribute("role", condition.getRole());   //输入用户角色信息
        model.addAttribute("roleList", roleList);    //角色信息
        model.addAttribute("pageInfo", pageInfo);    //分页
        model.addAttribute("userList", pageInfo.getList());  //查询到的用户信息
//        String str = null;
//        str.charAt(0);
        return "user/list";
    }

    /**
     * 局部异常
     */
    @ExceptionHandler({NullPointerException.class})
    public String exceptionHandler(Throwable throwable, HttpServletRequest request) {
        System.out.println("throwable = " + throwable.getMessage());
        request.setAttribute("exception","***" + throwable.getMessage() + "***");
        return "error";
    }

    /**
     * 查看
     */
    @RequestMapping(value = "/toView/{userId}")
    @ResponseBody
    public Object toView(@PathVariable Long userId) {
        User user = this.userService.findById(userId);
        return user;    //mvc配置文件中已配置自动转换json对象
    }

    /**
     * 查询用户编码是否存在
     */
    @RequestMapping("/doUserCode")
    @ResponseBody
    public String doUserCode(String userCode) {
        Integer count = this.userService.findByUserCode(userCode);
        return count.toString();
    }

    public void fetchRoleList(Model model) {
        model.addAttribute("roleList", this.roleService.findRole());
    }

    /**
     * 添加
     */
    @RequestMapping("/toAdd")
    public String toAdd(Model model) {
        List<Role> roleList = this.roleService.findRole();
        model.addAttribute("roleList", roleList);    //角色信息
        return "user/useradd";
    }

    @RequestMapping("/doAdd")
    public String doAdd(@Valid User user, BindingResult result, Model model, @RequestParam(value = "pic", required = false) MultipartFile[] pic, HttpSession session) throws Exception {

        if (pic != null) {
            //允许的文件扩展名
            List<String> allowedFileExtendsName = Arrays.asList(".jpn", ".png", ".gig", ".jpeg");
            String extendsName = null;
            //获取图片的真实路径(File.separator:符号/or\)
            String serverDirectory = session.getServletContext().getRealPath(File.separator + "headPic");
            String fileName = null;
            File destination = null;
            StringBuilder builder = new StringBuilder();
            for (MultipartFile thiPic : pic) {
                //判断上传来的图片是否为空
                if (thiPic.isEmpty() == false) {
                    //截取文件名后缀获取文件名
                    extendsName = thiPic.getOriginalFilename().substring(thiPic.getOriginalFilename().lastIndexOf("."));
                    if (allowedFileExtendsName.contains(extendsName.toLowerCase()) == false) {
                        throw new Exception("文件名扩展名不被允许,只允许.jpn,.png,.gig,.jpeg");
                    }
                    //截取上传图片的后缀,并且拼接上现在的时间+(0~9999)的随机数,生成新的文件名
                    fileName = System.currentTimeMillis() + "-" + new Random().nextInt(9999) + "-head" + extendsName;
                    destination = new File(serverDirectory, fileName);
                    thiPic.transferTo(destination);
                    builder.append(fileName + ",");
                }
            }
            System.out.println("builder = " + builder);
            user.setUserPicName(builder.substring(0, builder.length() - 1));
        }


        if (result.hasErrors()) {
            fetchRoleList(model);
            return "user/useradd";
        }
        int r = this.userService.add(user);
        if (r < 0) {
            return "redirect:toAdd?flag=-1";
        }
        return "redirect:show";
    }

    /**
     * 删除
     */
    @RequestMapping("/doRemove")
    public void doRemove(long userId, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        int r = this.userService.remove(userId);
        out.print(r);
    }

    /**
     * 修改
     */
    @RequestMapping("/toModif")
    public String toModif(Model model, User user) {
        List<Role> roleList = this.roleService.findRole();
        model.addAttribute("roleList", roleList);    //角色信息
        model.addAttribute("user", user);    //角色信息
        return "user/usermodif";
    }

    @RequestMapping("/doModif")
    public String doModif(@Valid User user, BindingResult result, HttpServletResponse response, Model model) throws IOException {
        if (result.hasErrors()) {
            fetchRoleList(model);
            return "user/usermodif";
        }
        PrintWriter out = response.getWriter();
        int r = this.userService.modif(user);
        if (r < 0) {
            return "redirect:toModif?flag=-1";
        }
        return "redirect:show";
    }

    /**
     * 修改密码
     */
    @RequestMapping("/toModifPwd")
    public String toModifPwd() {
        return "user/pwdmodif";
    }

    @RequestMapping("/doModifPwd")
    public String doModifPwd(String oldpassword, String newpassword, String rnewpassword, Long userId) {
        String findOldPassword = this.userService.findOldPassword(userId);
        if (!oldpassword.equals(findOldPassword)) {
            return "redirect:toModifPwd?flag=-1";
        }
        if (!newpassword.equals(rnewpassword)) {
            return "redirect:toModifPwd?flag=-2";
        }
        this.userService.updatePassword(userId, newpassword);
        return "redirect:/toLogin";
    }

    @RequestMapping(value = "/showUser", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String showUser(User user) {

        return "{\"userId\":" + user.getUserId() + ",\"userCode\":\"" + user.getUserCode() + "\",\"userName\":\"" + user.getUserName() + "\"}";
    }
}
